package org.eclipse.rally.plugin.views;

import org.eclipse.jface.window.ApplicationWindow;

import org.eclipse.rally.plugin.utils.IOString;
import org.eclipse.rally.plugin.utils.SWTResourceManager;
import org.eclipse.rally.plugin.utils.StreamDesEncrypter;
import org.eclipse.rally.plugin.webservice.RallyMain;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


public class LoginWindow extends ApplicationWindow {
    public static LoginWindow loginWindow;
    final Display display = Display.getCurrent();
    Shell shell = new Shell(display, SWT.NO_TRIM);
    Text txt_Password;
    Text txt_Username;
    Label lblLogin;
    Label lblCancel;
    Composite composite;
    String[] credentials = { "", "" };
    boolean exitRallyBeforeLogin;
    boolean login;
    File file = new File("plugins/rcache.jar");
    final Cursor handCursor = new Cursor(display, SWT.CURSOR_HAND);
    final Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
    StreamDesEncrypter encrypter = new StreamDesEncrypter("pASSW0RD123");

    LoginWindow() {
        super(null);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        loginWindow = new LoginWindow();
        loginWindow.setShellStyle(SWT.NONE);
        loginWindow.setBlockOnOpen(true);
        loginWindow.open();
        Display.getCurrent().dispose();
    }

    public Control createContents(final Composite parent) {
        parent.addDisposeListener(new DisposeListener() {
                public void widgetDisposed(DisposeEvent arg0) {
                    if (!login) {
                        exitRallyBeforeLogin = true;
                        System.out.println("CLOSING LOGIN WINDOW");
                    }
                }
            });
        credentials = readCredentials();

        parent.setBackground(SWTResourceManager.getColor(
                SWT.COLOR_WIDGET_LIGHT_SHADOW));
        composite = new Composite(parent, SWT.NONE);
        composite.setBounds(0, 0, 600, 600);
        composite.setBackground(SWTResourceManager.getColor(
                SWT.COLOR_WIDGET_BACKGROUND));
        composite.setLayout(null);

        final CLabel clbl_Username = new CLabel(composite, SWT.NONE);
        clbl_Username.setImage(SWTResourceManager.getImage(LoginWindow.class,
                "/icons/Login-enabled.gif"));

        //Setin Label for Login
        final CLabel clbl_UserLogin = new CLabel(composite, SWT.NONE);
        clbl_UserLogin.setBackground(SWTResourceManager.getColor(
                SWT.COLOR_LIST_BACKGROUND));
        clbl_UserLogin.setImage(SWTResourceManager.getImage(LoginWindow.class,
                "/icons/icon-rally.gif"));

        clbl_UserLogin.setBounds(0, 0, 340, 34);
        clbl_UserLogin.setText("Rally Login");

        Font font = new Font(composite.getDisplay(), "Arial Black", 12,
                SWT.NORMAL);

        clbl_UserLogin.setFont(font);

        clbl_Username.setBounds(44, 50, 65, 20);
        clbl_Username.setText("Username :");
        txt_Username = new Text(composite, SWT.BORDER);
        txt_Username.setBounds(115, 50, 161, 20);
        txt_Username.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent event) {
                    if (event.keyCode == SWT.ESC) {
                        exitRallyBeforeLogin = true;
                        System.out.println("USER NAME ECSAPE");
                        close();
                    }
                }
            });

        txt_Username.addListener(SWT.DefaultSelection,
            new Listener() {
                public void handleEvent(Event e) {
                    System.out.println("IN SWT.DefaultSelection");

                    String selected = txt_Username.getText();
                    String selected1 = txt_Password.getText();

                    if ((selected == "") && (selected1 == "")) {
                        MessageBox messageBox = new MessageBox(shell,
                                SWT.OK | SWT.ICON_WARNING);
                        messageBox.setMessage(
                            "Enter the User Name and Password");
                        messageBox.open();
                        txt_Username.setFocus();
                    } else if (selected == "") {
                        MessageBox messageBox = new MessageBox(shell,
                                SWT.OK | SWT.ICON_WARNING);
                        messageBox.setMessage("Enter the User Name");
                        messageBox.open();
                        txt_Username.setFocus();
                    } else if (selected1 == "") {
                        MessageBox messageBox = new MessageBox(shell,
                                SWT.OK | SWT.ICON_WARNING);
                        messageBox.setMessage("Enter the Password");
                        messageBox.open();
                        txt_Password.setFocus();
                    }
                }
            });

        txt_Username.addSelectionListener(new SelectionAdapter() {
                public void widgetDefaultSelected(SelectionEvent e) {
                    System.out.println("IN SelectionAdapter()");
                    txt_Username.setCursor(waitCursor);
                    processLoginValidation(parent);
                }
            });

        //Label for the password
        final CLabel clbl_Password = new CLabel(composite, SWT.NONE);
        clbl_Password.setBounds(44, 82, 65, 20);
        clbl_Password.setText("Password :");

        txt_Password = new Text(composite, SWT.BORDER);
        txt_Password.setBounds(115, 82, 161, 20);

        if (credentials.length == 2) {
            //set the cached credentials
            txt_Username.setText(credentials[0]);
            txt_Password.setText(credentials[1]);
        }

        txt_Password.setEchoChar('*');
        txt_Password.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent event) {
                    if (event.keyCode == SWT.ESC) {
                        exitRallyBeforeLogin = true;
                        System.out.println("PASSWORD ECSAPE");
                        close();
                    }
                }
            });
        txt_Password.addSelectionListener(new SelectionAdapter() {
                public void widgetDefaultSelected(SelectionEvent e) {
                	txt_Password.setCursor(waitCursor);
                    processLoginValidation(parent);
                }
            });

        String message = "<a>Forgot your password?</a>";

        lblLogin = new Label(composite, SWT.NONE);
        lblLogin.setText("login");
        lblLogin.setCursor(handCursor);
        lblLogin.setImage(SWTResourceManager.getImage(LoginWindow.class,
                "/icons/Login-enabled.gif"));
        lblLogin.setBounds(120, 115, 56, 25);

        {
            lblCancel = new Label(composite, SWT.NONE);
            lblCancel.setImage(SWTResourceManager.getImage(LoginWindow.class,
                    "/icons/Cancel-enabled.gif"));
            lblCancel.setBounds(213, 115, 58, 25);

            Label label_1 = new Label(composite, SWT.NONE);
            label_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
            label_1.setBounds(0, 35, 340, 4);

            lblCancel.setCursor(handCursor);

            lblCancel.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseDown(MouseEvent e) {
                        try {
                        	lblCancel.setCursor(waitCursor);
                            exitRallyBeforeLogin = true;
                            System.out.println("CANCEL BUTTON CLOSE");
                            close();
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                });
        }

        lblLogin.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseDown(MouseEvent e) {
                	lblLogin.setCursor(waitCursor);
                    processLoginValidation(parent);
                }
            });

        return composite;
    }

    //reads the last logged in credentials
    public String[] readCredentials() {
        System.out.println("In readCredentials @@@@@@@@@@");

        String[] credentials = { "", "" };

        try {
            System.out.println("file.createNewFile()==" + file.createNewFile());

            IOString ios = new IOString();
            encrypter.decrypt(new FileInputStream(file), ios.getOutputStream());

            String line = ios.getString();

            if (line != null) {
                credentials = line.split("/");
                System.out.println("creds in new == " + line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return credentials;
    }

    // cache the last entered credentials
    public void cacheCredentials(String newCreds) {
        System.out.println("In cacheCredentials @@@@@@@@@@");

        try {
            if (file.exists()) {
                /*  fop.write(newCreds.getBytes());
                  fop.flush();
                  fop.close();*/
                encrypter.encrypt(new IOString(newCreds).getInputStream(),
                    new FileOutputStream(file));
            } else {
                System.out.println("Cache File  does not exist");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void processLoginValidation(Composite parent) {
        boolean user = false;
        boolean pwd = false;
        String selected = txt_Username.getText();
        String selected1 = txt_Password.getText();
        if ((selected == "") && (selected1 == "")) {
            user = true;

            MessageBox messageBox = new MessageBox(shell,
                    SWT.OK | SWT.ICON_WARNING);
            messageBox.setMessage("Enter the User Name and Password");
            messageBox.open();
            txt_Username.setFocus();
        } else if (selected == "") {
            user = true;

            MessageBox messageBox = new MessageBox(shell,
                    SWT.OK | SWT.ICON_WARNING);
            messageBox.setMessage("Enter the User Name");
            messageBox.open();
            txt_Username.setFocus();
        } else if (selected1 == "") {
            pwd = true;

            MessageBox messageBox = new MessageBox(shell,
                    SWT.OK | SWT.ICON_WARNING);
            messageBox.setMessage("Enter the Password");
            messageBox.open();
            txt_Password.setFocus();
        }

        if (!user & !pwd) {
            System.out.println("UN =" + selected + "::: PWD =" + selected1);

            try {
                login = RallyMain.validateUserLogin(selected, selected1);

                if (login) {
                    System.out.println("Login Success");

                    if (credentials[0].equals("") ||
                            !(credentials[0].equals(txt_Username.getText()))) {
                        System.out.println("1@@@: " + txt_Username.getText() +
                            "/" + txt_Password.getText());
                        cacheCredentials(txt_Username.getText() + "/" +
                            txt_Password.getText());
                    }

                    parent.dispose();
                } else {
                    System.out.println("Login Failed");
                    System.out.println("UN & PWD Entered");

                    MessageBox messageBox = new MessageBox(shell,
                            SWT.OK | SWT.ICON_WARNING);
                    messageBox.setMessage(
                        "Invalid User Credentials. Please try again!");
                    messageBox.open();
                    txt_Username.setText("");
                    txt_Password.setText("");
                }
            } catch (Exception eq) {
                System.out.println("Login Failed");

                MessageBox messageBox = new MessageBox(shell,
                        SWT.OK | SWT.ICON_WARNING);
                messageBox.setMessage(
                    "Invalid User Credentials. Please try again!");
                messageBox.open();
                txt_Username.setFocus();
                txt_Username.setText("");
                txt_Password.setText("");

                System.out.println("Exception on Login :" + eq);

                //e.printStackTrace();
            }
        }

        user = false;
        pwd = false;
    }
}
